package com.letfox.common.exception;

import com.letfox.common.enums.ErrorEnum;

/**
 * 自定义异常处理
 */
public class CustomerException extends RuntimeException{
	
	private static final long serialVersionUID = 3380527655305563701L;
	
	private String code;
    private String message;
    private ErrorEnum errorEnum;
    
	public CustomerException(ErrorEnum errorEnum, Throwable cause) {
		super("[" + errorEnum.getCode() + "]" + errorEnum.getDesc(), cause);
		this.errorEnum = errorEnum;
		this.code = errorEnum.getCode();
		this.message = errorEnum.getDesc();
		
		if(cause != null){
			if (cause instanceof CustomerException) {
				CustomerException customerException = (CustomerException) cause;
                this.code = customerException.getCode();
                this.message = customerException.getMessage();
            } else {
                if (null != cause.getMessage() && cause.getMessage().indexOf("ConstraintViolationException") != -1 && cause.getMessage().contains("Duplicate entry")) {
                    errorEnum = ErrorEnum.E001;
                    int startIndex = cause.getMessage().indexOf("Duplicate entry");
                    int endIndex = cause.getMessage().indexOf("for key");
                    this.code = errorEnum.getCode();
                    this.message = "[" + errorEnum.getCode() + "]" + cause.getMessage().substring(startIndex + "Duplicate entry".length(), endIndex) + errorEnum.getDesc();
                }
            }
		}
	}
	
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public ErrorEnum getErrorEnum() {
		return errorEnum;
	}
	public void setErrorEnum(ErrorEnum errorEnum) {
		this.errorEnum = errorEnum;
	}
	
	@Override
	public String toString() {
		return "CustomerException [code=" + code + ", message=" + message + ", errorEnum=" + errorEnum + "]";
	}
}
